package org.dromara.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.Coupon;
import org.dromara.business.domain.bo.CouponBo;
import org.dromara.business.domain.vo.CouponVo;
import org.dromara.business.domain.vo.GoodsCouponVo;
import org.dromara.business.mapper.CouponMapper;
import org.dromara.business.service.CouponService;
import org.dromara.business.service.GoodsCouponService;
import org.dromara.business.service.UserFlowingService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 拼团优惠券Service业务层处理
 *
 * @author zlj
 * @date 2025-04-27
 */
@RequiredArgsConstructor
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    private final CouponMapper baseMapper;
    private final UserFlowingService flowingService;
    @Resource
    @Lazy
    private GoodsCouponService goodsCouponService;

    /**
     * 查询拼团优惠券
     */
    @Override
    public CouponVo queryById(Long couponId) {
        return baseMapper.selectVoById(couponId);
    }

    /**
     * 查询拼团优惠券列表
     */
    @Override
    public TableDataInfo<CouponVo> queryPageList(CouponBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Coupon> lqw = buildQueryWrapper(bo);
        Page<CouponVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询拼团优惠券列表
     */
    @Override
    public List<CouponVo> queryList(CouponBo bo) {
        LambdaQueryWrapper<Coupon> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Coupon> buildQueryWrapper(CouponBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Coupon> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAmount() != null, Coupon::getAmount, bo.getAmount());
        lqw.eq(bo.getGoodsCouponId() != null, Coupon::getGoodsCouponId, bo.getGoodsCouponId());
        lqw.eq(bo.getCreateBy() != null, Coupon::getCreateBy, bo.getCreateBy());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), Coupon::getStatus, bo.getStatus());
        lqw.eq(LoginHelper.isUser(), Coupon::getCreateBy, LoginHelper.getUserId());
        lqw.le(ObjectUtil.isNotNull(bo.getGoodsAmount()), Coupon::getConditionAmount, bo.getGoodsAmount());
        lqw.orderByDesc(Coupon::getCreateTime);
        return lqw;
    }

    /**
     * 新增拼团优惠券
     */
    @Override
    public Boolean insertByBo(CouponBo bo) {
        Coupon add = MapstructUtils.convert(bo, Coupon.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCouponId(add.getCouponId());
        }
        return flag;
    }

    /**
     * 修改拼团优惠券
     */
    @Override
    public Boolean updateByBo(CouponBo bo) {
        Coupon update = MapstructUtils.convert(bo, Coupon.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Coupon entity) {

    }

    /**
     * 批量删除拼团优惠券
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 领取优惠卷
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receive(Long configId) {
        GoodsCouponVo goodsCouponVo = goodsCouponService.queryById(configId);
        if (ObjectUtil.isNull(goodsCouponVo) || goodsCouponVo.getStartTime().after(new Date()) || goodsCouponVo.getEndTime().before(new Date())) {
            throw new ServiceException("该优惠券不存在");
        }
        flowingService.addAmount(LoginHelper.getUserId(), goodsCouponVo.getPrice().multiply(new BigDecimal("-1")),
            BusinessConstants.FLOWING_TYPE_COUPON, configId, BusinessConstants.FLOWING_TYPE_INTEGRAL);
        //新增领取记录
        Coupon coupon = new Coupon();
        coupon.setGoodsCouponId(configId);
        coupon.setName(goodsCouponVo.getName());
        coupon.setRemark(goodsCouponVo.getInfo());
        coupon.setAmount(goodsCouponVo.getAmount());
        coupon.setConditionAmount(goodsCouponVo.getConditionAmount());
        return this.save(coupon);
    }
}
